#include <thread>
#include "../../client/requestor.hpp"
#include "../../client/rpc_caller.hpp"
#include "../../common/dispatcher.hpp"

void callback(const Json::Value & result)
{
    LOG(INFO,"call back result:%d",result.asInt());
}

int main()
{
    //实例化requestor,进行消息管理
    auto requestor = std::make_shared<rpc::client::Requestor>();
    //通过caller向服务端发送请求,服务端处理完毕,客服端需要针对服务端的响应进行处理
    auto caller = std::make_shared<rpc::client::RpcCaller>(requestor);//RpcCaller包含requestor对象

    std::shared_ptr<rpc::Dispatcher> dispatcher = std::make_shared<rpc::Dispatcher>();//创建dispatcher进行注册
    auto rsp_cb = std::bind(&rpc::client::Requestor::onResponse, requestor.get(), std::placeholders::_1, std::placeholders::_2);

    //管理消息的是requestor,通过requestor的回调进行处理Rpc响应
    dispatcher->registerHandler<rpc::BaseMessage>(rpc::MType::RSP_RPC, rsp_cb);//这里是BaseMessage,对应onResponse的参数类型
    rpc::BaseClient::ptr client = rpc::ClientFactory::create("127.0.0.1", 9090);
    rpc::MessageCallback message_cb = std::bind(&rpc::Dispatcher::onMessage, dispatcher.get(), std::placeholders::_1, std::placeholders::_2);
    client->setMessageCallback(message_cb);
    client->connect();
    auto conn = client->connection();//获取连接
    Json::Value params, result;
    params["num1"] = 11;
    params["num2"] = 22;
    bool ret = caller->call(conn, "Add", params, result);//进行Rpc调用,result进行获取结果
    if (ret != false)
    {
        std::cout << "result:" << result.asInt() << std::endl;
    }

    //异步调用
    rpc::client::RpcCaller::JsonAsyncResponse res_future;
    params["num1"] = 33;
    params["num2"] = 22;
    ret = caller->call(conn, "Add", params, res_future);
    if (ret != false)
    {
        result = res_future.get();
        std::cout << "result:" << result.asInt() << std::endl;
    }

    //回调函数回调
    params["num1"] = 55;
    params["num2"] = 66;
    ret = caller->call(conn, "Add", params, callback);
    LOG(INFO,"---------");
    std::this_thread::sleep_for(std::chrono::seconds(10));
    client->shutdown();//关闭连接,退出
    return 0;
}
